package com.example.blueconn.fragment.bl;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.blueconn.Constant;
import com.example.blueconn.R;
import com.example.blueconn.databinding.FragmentBlSelectBinding;
import com.example.blueconn.manager.FastBleManager;
import com.example.blueconn.manager.PreferenceManager;

/**
 * Created by zhudongao
 * Desc
 * Date 4/5/21
 */

public class BLSelectFragment  extends Fragment{
    private FragmentBlSelectBinding dataBinding;
    private BlRecyclerAdapter adapter;

    public BLSelectFragment() {
        // Required empty public constructor
    }

    public static BLSelectFragment newInstance() {
        return new BLSelectFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_bl_select, container, false);
        initView();
        return dataBinding.getRoot();
    }

    private void initView() {
        adapter = new BlRecyclerAdapter();
        dataBinding.recycler.setAdapter(adapter);
        dataBinding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));

        dataBinding.blScan.setOnClickListener(v -> {
            adapter.clearData();
            FastBleManager.getInstance().scanBle();
        });

        FastBleManager.getInstance().scanBle();

        FastBleManager.getInstance().getScanTipMsg().observe(getViewLifecycleOwner(), s -> dataBinding.scanTip.setText("(" + s + ")"));

        FastBleManager.getInstance().getBleDeviceObservable().observe(getViewLifecycleOwner(), bleDevice -> {
            BlBean blBean = new BlBean();
            blBean.setBlName(bleDevice.getName());
            blBean.setMac(bleDevice.getMac());
            adapter.addItem(blBean);
        });

        dataBinding.configure.setOnClickListener(v -> {
            BlBean bl = adapter.getSelectItem();
            if (bl == null) {
                Toast.makeText(getContext(), "请选择连接的设备，再点击确定", Toast.LENGTH_SHORT).show();
            } else {
                PreferenceManager.getInstance().putString(Constant.BL_MAC_NAME, bl.getBlName());
                PreferenceManager.getInstance().putString(Constant.BL_MAC_ADDRESS, bl.getMac());
                FastBleManager.getInstance().connect(bl.getMac());
                FastBleManager.recon.postValue(true);
                if (getActivity() != null) {
                    getActivity().finish();
                }
            }
        });
    }
}
